package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.common.util.RequestUtils;
import com.mars.common.util.TokenUtils;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.SysCollectionMapper;
import com.mars.module.admin.mapper.SysDictDataMapper;
import com.mars.module.admin.mapper.SysProductMapper;
import com.mars.module.admin.mapper.SysShopMapper;
import com.mars.module.admin.request.SysCollectionRequest;
import com.mars.module.admin.service.ISysCollectionService;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户收藏业务层处理
 *
 * @author mars
 * @date 2024-01-25
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysCollectionServiceImpl implements ISysCollectionService {

    private final SysCollectionMapper baseMapper;
    private final SysProductMapper productMapper;
    private final SysUserMapper userMapper;
    private final SysShopMapper shopMapper;
    private final SysDictDataMapper dictDataMapper;
    private final TokenUtils tokenUtils;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysCollection add(SysCollectionRequest request) {
        SysCollection entity = SysCollection.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        entity.setUserId(userId);
        Long count = baseMapper.selectCount(new QueryWrapper<SysCollection>().eq("user_id", userId)
                .eq("other_id", request.getOtherId()).eq("collection_type", "1"));
        if (count == 0L) {
            baseMapper.insert(entity);
        }
        return entity;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        Long l = ids.stream().findFirst().orElse(null);
        return baseMapper.delete(new QueryWrapper<SysCollection>().eq("user_id", ContextUserInfoThreadHolder.get().getId())
                .eq("other_id", l.toString()).eq("collection_type", "1")) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysCollectionRequest request) {
        SysCollection entity = SysCollection.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysCollection getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysCollection> pageList(SysCollectionRequest request) {
        HttpServletRequest servletRequest = RequestUtils.getRequest();
        Long userId = tokenUtils.getUserId(servletRequest);
        request.setUserId(userId);
        Page<SysCollection> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysCollection> query = this.buildWrapper(request);
        IPage<SysCollection> pageRecord = baseMapper.selectPage(page, query);
        List<SysCollection> records = pageRecord.getRecords();
        List<SysCollection> recordsNew = new ArrayList<>();
        for (SysCollection collection : records) {
            if (collection.getCollectionType() == 1) {
                SysProduct sysProduct = productMapper.selectById(collection.getOtherId());
                collection.setOtherName(sysProduct == null ? "" : sysProduct.getName());
                collection.setPicture(sysProduct == null ? "" : sysProduct.getPicture());
            } else if (collection.getCollectionType() == 2) {
                SysShop shop = shopMapper.selectById(collection.getOtherId());
                collection.setOtherName(shop == null ? "" : shop.getShopName());
            }
            SysUser sysUser = userMapper.selectById(collection.getUserId());
            collection.setUserName(sysUser == null ? "" : sysUser.getUserName());
            collection.setCollectionName(getStatusName(String.valueOf(collection.getCollectionType()), "collection_type"));
            recordsNew.add(collection);
        }
        if (StringUtils.isNotBlank(request.getProductName())) {
            recordsNew = recordsNew.stream().filter(e -> e.getOtherName().contains(request.getProductName())).collect(Collectors.toList());
        }
        recordsNew = recordsNew.stream().sorted((m1, m2) -> m2.getCreateTime().compareTo(m1.getCreateTime())).collect(Collectors.toList());
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }

    private String getStatusName(String value, String type) {
        List<SysDictData> reviewStatus = dictDataMapper.selectList(Wrappers.lambdaQuery(SysDictData.class)
                .eq(SysDictData::getDictType, type).orderByAsc(SysDictData::getDictSort));
        SysDictData sysDictData = reviewStatus.stream().filter(e -> value.equals(e.getDictValue())).findFirst().orElse(null);
        return sysDictData == null ? "" : sysDictData.getDictLabel();
    }

    @Override
    public List<SysCollection> list(SysCollectionRequest request) {
        LambdaQueryWrapper<SysCollection> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysCollection> buildWrapper(SysCollectionRequest param) {
        LambdaQueryWrapper<SysCollection> query = new LambdaQueryWrapper<>();
        if (param.getCollectionType() != null) {
            query.eq(SysCollection::getCollectionType, param.getCollectionType());
        }
        if (param.getUserId() != null) {
            query.eq(SysCollection::getUserId, param.getUserId());
        }
        return query;
    }

}
